//
//  AlertViewManager.m
//  Answern
//
//  Created by TobyYoung on 2017/5/10.
//  Copyright © 2017年 Answern. All rights reserved.
//

#import "AlertViewManager.h"
#import <objc/runtime.h>

@interface BlockAlertView : UIAlertView<UIAlertViewDelegate>
- (id)initWithTitle:(NSString *)title
            message:(NSString *)message
  cancelButtonTitle:(NSString *)cancelButtonTitle
 confirmButtonTitle:(NSString*)confirmButtonTitle
              block:(AlertViewBlock)block;
@end

@implementation BlockAlertView

static char alertViewTag;

- (id)initWithTitle:(NSString *)title message:(NSString *)message cancelButtonTitle:(NSString *)cancelButtonTitle confirmButtonTitle:(NSString *)confirmButtonTitle block:(AlertViewBlock)block{
    self = [super initWithTitle:title
                        message:message
                       delegate:self
              cancelButtonTitle:cancelButtonTitle
              otherButtonTitles:confirmButtonTitle, nil];
    
    objc_setAssociatedObject(self, &alertViewTag, block, OBJC_ASSOCIATION_COPY_NONATOMIC);
    
    return self;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    AlertViewBlock aBlock = objc_getAssociatedObject(self, &alertViewTag);
    if (aBlock) {
        aBlock(buttonIndex);
    }
}

- (void)dealloc{
    
    objc_removeAssociatedObjects(self);
}

@end

@interface AlertViewManager() {
    
    id alertView;
}

@end

@implementation AlertViewManager

- (id)initWithTitle:(NSString *)title message:(NSString *)message cancelButtonTitle:(NSString *)cancelButtonTitle confirmButtonTitle:(NSString *)confirmButtonTitle delegate:(id)delegate block:(AlertViewBlock)block {
    
    self = [super init];
    
    if (self) {

        alertView = [[BlockAlertView alloc]initWithTitle:title message:message cancelButtonTitle:cancelButtonTitle confirmButtonTitle:confirmButtonTitle block:block];
    }
    
    return self;
}

- (void)show{
    
    BlockAlertView *alert = alertView;
    [alert show];
}

- (void)dealloc{
    
    alertView = nil;
}

@end
